//
//  SDFeedbackViewController.m
//  SKinDiary
//
//  Created by pcyang on 16/9/4.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "SDFeedbackViewController.h"
#import "SDFeedbackData.h"
#import "SDFormBaseData.h"

#define kSettingConnectDes  @"您的宝贵意见将帮助我们不断改进："
#define kAdviceHint         @"期待您的反馈"


@interface SDFeedbackViewController ()<UITextViewDelegate, SDFormBaseDataDelegate>
{
    UITextView *_tvAdvice;
    UIButton *_btnSend;
    UILabel *tsLabel;
    
    BOOL _isSendSucess;
}

@property(nonatomic,strong) SDFeedbackData  *feedbackData;

@end

@implementation SDFeedbackViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"意见反馈";
    
    [self initViews];
}

- (void)initViews
{
    BOOL naviHidden = [self navigationBarHidden];
    if (!naviHidden && self.navBar != nil)
    {
        [self.navBar setTitle:@"意见反馈"];
        UIImage* addImg = LOAD_IMAGE_USE_CACHE_INBUNDLE(DefaultBundle, @"actionbar_btn_back.png");
        [self.navBar customNaviLeftButton:self action:@selector(onBack:) image:addImg];
    }
    
    self.view.backgroundColor = [@"f0f0f0" toUIColor];
    
    // TextView 下方的提示语
    CGFloat offset = kNavBarHeight;
    UILabel *lblTip = [[UILabel alloc] initWithFrame:autoRectMakeWithoutY(15, offset, 270, 40)];
    lblTip.backgroundColor = [UIColor clearColor];
    lblTip.font = [UIFont systemFontOfSize:14];
    lblTip.textColor = [@"434549" toUIColor];
    //lblTip.lineBreakMode = UILineBreakModeWordWrap;
    lblTip.numberOfLines = 1;
    lblTip.text = kSettingConnectDes;
    [self.view addSubview:lblTip];
    
    
    // TextView 的白色圆角背景
    offset = kNavBarHeight +autoLayoutHeight(40);
    UIImage *tImage = LOAD_IMAGE_USE_CACHE_INBUNDLE(SettingsPageBundle, @"setting_advice_textbg.png");
    UIImage *stretchImage = [tImage stretchableImageWithLeftCapWidth:5 topCapHeight:5];
    UIImageView *ivBgForTextView = [[UIImageView alloc] initWithImage:stretchImage];
    ivBgForTextView.frame = autoRectMakeWithoutY(15, offset, 290, 120);
    [self.view addSubview:ivBgForTextView];
    
    _tvAdvice = [[UITextView alloc] init];
    _tvAdvice.frame = autoRectMakeWithoutY(30, offset+7.5f, 260, 105);
    _tvAdvice.bounces = YES;
    _tvAdvice.backgroundColor = [UIColor clearColor];
    _tvAdvice.textAlignment = NSTextAlignmentLeft;
    //_tvAdvice.backgroundColor = [UIColor clearColor];
    _tvAdvice.keyboardAppearance = UIKeyboardAppearanceAlert;
    _tvAdvice.font = [UIFont systemFontOfSize:14];
    _tvAdvice.textColor = [UIColor colorWithRGB:0xa2a5a8];
    _tvAdvice.delegate = self;
    _tvAdvice.text = kAdviceHint;
    [self.view addSubview:_tvAdvice];
    
    offset = kNavBarHeight +autoLayoutHeight(169);
    tsLabel = [[UILabel alloc] initWithFrame:autoRectMakeWithoutY(15, offset, 270, 12)];
    tsLabel.textColor = [@"a2a5a8" toUIColor];
    tsLabel.font = [UIFont systemFontOfSize:autoLayoutHeight(12)];
    tsLabel.text = @"还可以输入200字";
    [self.view addSubview:tsLabel];
    
    offset += (12+15);
    _btnSend = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnSend.frame = autoRectMakeWithoutY(15.f, offset, 290.f, 35.f);
    [_btnSend setBackgroundColor:[@"24d9c6" toUIColor]];
    [_btnSend setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_btnSend setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
    [_btnSend setTitle:@"发    送" forState:UIControlStateNormal];
    [_btnSend setEnabled:NO];
    _btnSend.titleLabel.font = [UIFont systemFontOfSize:16.f];
    [_btnSend addTarget:self action:@selector(clickedBtnSend:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnSend];
    
    UILabel *twoLab = [[UILabel alloc] init];
    twoLab.backgroundColor = [UIColor clearColor];
    twoLab.textColor = [@"677fad" toUIColor];
    twoLab.textAlignment = NSTextAlignmentLeft;
    twoLab.font = [UIFont systemFontOfSize:12.f];
    twoLab.text = @"QQ群: ";
    [twoLab sizeToFit];
    twoLab.center = CGPointMake(self.view.width/2.f, self.view.height-50.f-twoLab.height/2.f);
  //  [self.view addSubview:twoLab];
    
    UILabel* oneLab = [[UILabel alloc] init];
    oneLab.backgroundColor = [UIColor clearColor];
    oneLab.textColor = [@"a2a5a8" toUIColor];
    oneLab.textAlignment = NSTextAlignmentLeft;
    oneLab.font = [UIFont systemFontOfSize:12.f];
    oneLab.text = @"意见反馈请联系我们";
    [oneLab sizeToFit];
    oneLab.center = CGPointMake(self.view.width/2.f, twoLab.top-10.f-oneLab.height/2.f);
   // [self.view addSubview:oneLab];

}

- (void)onBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [_tvAdvice resignFirstResponder];
    
    if (self.feedbackData)
    {
        if ( _isSendSucess )
        {
            _tvAdvice.text = kAdviceHint;
        }
        else
        {
            _isSendSucess = YES;
        }
    }
}



- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_tvAdvice resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ---

-(BOOL) navigationBarHidden
{
    return NO;
}


#pragma mark -
#pragma mark click button

- (void)clickedBtnSend:(id)sender
{
    if ([_tvAdvice.text isEqualToString:@""]) {
        return;
    }
    NSString *trimmedString = [_tvAdvice.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([trimmedString isEqualToString:@""])
        return;
    
    [_tvAdvice resignFirstResponder];
    _btnSend.enabled = NO;
    
    if(nil==_feedbackData)
    {
        _feedbackData = [[SDFeedbackData alloc] init];
        _feedbackData.delegate = self;
    }
    
    NSString* text = [[NSString alloc] initWithFormat:@"用户：%@\r\n版本：%@\r\n %@",[SDAccountInfoManager sharedInstance].nickName,
                      [SDAppUtils getAppBuildVersion], trimmedString];
    _feedbackData.content = text;
    [_feedbackData excuteHttpRequest];
}


#pragma mark -
#pragma mark UITextView delegate

- (void)textViewDidEndEditing:(UITextView *)textView;
{
}

- (void) textViewDidBeginEditing:(UITextView *)textView
{
    if ([_tvAdvice.text isEqualToString:kAdviceHint])
    {
        _tvAdvice.text = @"";
    }
    
    [self onEditingDone:nil];
}

- (void)textViewDidChange:(UITextView *)textView
{
    UITextRange *textRange = textView.markedTextRange;
    
    if (!textRange.start || !textRange.end) {
        if (textView.text.length > 200)
        {
            _tvAdvice.text = [textView.text substringToIndex:200];
            
            tsLabel.text = @"还可以输入0字符";
        }
        else
        {
            NSInteger num = 200-(unsigned long)textView.text.length;
            tsLabel.text = [NSString stringWithFormat:@"还可以输入%ld字符",(long)num];
        }
    }
    [self onEditingDone:nil];
}

- (BOOL)canSend
{
    BOOL cans = [_tvAdvice hasText] && ([[_tvAdvice.text stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\n "]] length] != 0);
    BOOL isWrite = [_tvAdvice.text isEqualToString:kAdviceHint];
    return cans && !isWrite;
}

- (void)onEditingDone:(id)sender
{
    _btnSend.enabled = [self canSend];
}


- (void)showLoadingWith:(NSString*)text
{
    [self finishLoading];
    [VPMBProgressHUD showIndicatorWithText:text];
}

- (void)finishLoading
{
    [VPMBProgressHUD hideIndicator];
}

- (void)failedLoading
{
    [self finishLoading];
    [VPMBProgressHUD showAttendAlert:@"发送失败" andIcon:nil];
}

#pragma mark -
#pragma mark response to server

- (void)sendError
{
    _isSendSucess = NO;
    _btnSend.enabled = YES;
    
    [SDAlertManagement showNetworkErrorAlert:@"发送失败"];
}

- (void)sendSuccess
{
    _isSendSucess = YES;
    _btnSend.enabled = NO;
    _tvAdvice.text = @"";
    
    [SDAlertManagement showNetworkErrorAlert:@"发送成功"];
    [self performSelector:@selector(popSelf) withObject:nil afterDelay:1.0];
    
}
- (void)popSelf
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -
#pragma mark rotate

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_5_1
- (BOOL) shouldAutorotate NS_AVAILABLE_IOS(6_0)
{
    return YES;
}

- (UIInterfaceOrientationMask) supportedInterfaceOrientations NS_AVAILABLE_IOS(6_0)
{
    return UIInterfaceOrientationMaskPortrait;
}

#endif


#pragma mark ---
#pragma mark  VPBaseDataDelegate <NSObject>

-(void) willUploadOfFormData:(SDFormBaseData*) formdata;
{
    [self showLoadingWith:@"发送中"];
}

-(void) formData:(SDFormBaseData*)formdata userInfo:(NSDictionary*) userInfo didFinishLoadWithError:(NSError*)error
{
    if (error == nil)
    {
        [self sendSuccess];
    }
    else
    {
        [self sendError];
    }
}

@end
